package com.wsk.controller;

import com.wsk.empty.Empty;
import com.wsk.encrypt.Encrypt;
import com.wsk.pojo.UserInformation;
import com.wsk.service.UserInformationService;
import com.wsk.service.UserPasswordService;
import com.wsk.token.TokenProccessor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

import static com.wsk.controller.RepeatSubmit.isRepeatSubmit;

/**
 * Created by wsk1103 on 2017/4/26.
 */
@Controller
public class UserInformationController {
    private static boolean hasCookie = true;
    @Resource(name = "userInformationService")
    private UserInformationService userInformationService;

    @Resource(name = "userPasswordService")
    private UserPasswordService userPasswordService;


    //This is a test which show all user`s information.
    @RequestMapping("/show")
    public String cc(HttpServletRequest request, Model model) {
        int id = Integer.parseInt(request.getParameter("id"));
        UserInformation userInformation = this.userInformationService.getUserInformationById(id);
        model.addAttribute("user", userInformation);
        return "showUser";
    }

    //This is a home when user login for my web
    @RequestMapping(value = "home",method = RequestMethod.GET)
    public String home(HttpServletRequest request,Model model) {
        String phone_session = (String) request.getSession().getAttribute("phone_session");
        String password_session = (String) request.getSession().getAttribute("password_session");
        if (AlwayLogin.isAlawLogin(phone_session,password_session,request)) {
            UserInformation userInformation = getUserInformation(phone_session);
            model.addAttribute("username", userInformation.getName());
            model.addAttribute("autograph", userInformation.getAutograph());
            return "home";
        }
        return "login";
    }
    @RequestMapping(value = "home", method = {RequestMethod.POST})
    public String home(@RequestParam String username, @RequestParam String password, @RequestParam String token,
                       Model model, HttpServletRequest request, HttpServletResponse response) {
        System.out.println(new Date() + ",run home");
        //if user login successful,the web will build a session which has a allow_token,the allow_token is used to discern user`s identity in the future.
//        String phone_session = (String) request.getSession().getAttribute("phone_session");
//        String password_session = (String) request.getSession().getAttribute("password_session");
        if (!Empty.isNullOrEmpty( request.getSession().getAttribute("allow_token"))) {
            UserInformation userInformation = getUserInformation(username);
            model.addAttribute("username", userInformation.getName());
            model.addAttribute("autograph", userInformation.getAutograph());
            return "home";
        }
        boolean b = isRepeatSubmit(token, (String) request.getSession().getAttribute("token"));
        if (b) {
            return login(model, request, response);
        } else {
            request.getSession().removeAttribute("token");
//            TokenProccessor.getInstance().deleteToken(request,"token");
        }
        String password_md5 = Encrypt.getMD5(password);
        if (login(username, password_md5,request)) {
            UserInformation userInformation = getUserInformation(username);
            model.addAttribute("username", userInformation.getName());
            model.addAttribute("autograph", userInformation.getAutograph());
            String allow_token = TokenProccessor.getInstance().makeToken();
            request.getSession().setAttribute("allow_token", allow_token);
            //put the phone and the password into session
            request.getSession().setAttribute("phone_session", username);
            request.getSession().setAttribute("password_session", password);
            request.getSession().setAttribute("true_phone",username);
            request.getSession().setAttribute("true_password",password);
            String remember_me = request.getParameter("remember_me");
            if (!Empty.isNullOrEmpty(remember_me)) {
                Cookie cookie = new Cookie("MovieWeb_username", username.trim());
                cookie.setMaxAge(60 * 60 * 24 * 7);
                response.addCookie(cookie);
                cookie = new Cookie("MovieWeb_password", password);
                cookie.setMaxAge(60 * 60 * 24 * 7);
                response.addCookie(cookie);
                hasCookie = true;
            }
            return "home";
        } else {
            model.addAttribute("username", username);
            model.addAttribute("error", "账号或者密码错误");
            hasCookie = false;
            return login(model, request, response);
        }
    }

//    @RequestMapping(value = "publishCritic",method = {RequestMethod.POST,RequestMethod.GET})
//    @ResponseBody
//    public Map publishCritic(HttpServletRequest request, HttpServletResponse response, Model model,
//                                @RequestParam(value = "file_upload", required = false) MultipartFile file_upload,
//                                @RequestParam String movie_name, @RequestParam String movie_content,@RequestParam int isPrivate) {
//        String phone_session = (String) request.getSession().getAttribute("phone_session");
//        String password_session = (String) request.getSession().getAttribute("password_session");
//        String path = "";
//        Map<String,String> map = new HashMap();
//        if (movie_content.length() < 1 || movie_name.length() <1 ) {
//            map.put("result", "0");
//            return map;
//        }
//        if (Empty.isNullOrEmpty(phone_session) || Empty.isNullOrEmpty(password_session)) {
//            map.put("result", "0");
//            return map;
//        }
//        if (Empty.isNullOrEmpty(file_upload)) {
//            map.put("result", "0");
//        } else {
//            path = request.getSession().getServletContext().getRealPath("userPicture");
////            path += "/image/userPicture/";
//            String fileName = Encrypt.getRandom() + new Date().getTime() + ".jpg";
////        System.out.println(path+"\\"+fileName);
//            File image = new File(path, fileName);
//            if (!image.exists())
//                image.mkdirs();
//            try {
//                file_upload.transferTo(image);
//            } catch (Exception e) {
//                map.put("result", "0");
//                e.printStackTrace();
//                return map;
//            }
//            path = "localhost:8080"+request.getContextPath() + "/" + phone_session + "/" + fileName;
//        }
//        PublishCritic publishCritic = new PublishCritic();
//        publishCritic.setCritic(movie_content);
//        publishCritic.setGood(0);
//        publishCritic.setIsprivate(isPrivate);
//        publishCritic.setPicture(path);
//        publishCritic.setTime(new Date());
//        publishCritic.setTitle(movie_name);
//        publishCritic.setUid((Integer) request.getSession().getAttribute("uid"));
//        publishCritic.setAllow((short) 1);
//        publishCritic.setModified(new Date());
//        int id_result = allService.insertObject(publishCritic);
//        if (id_result != 1) {
//            map.put("result", "0");
//            return map;
//        }
//        map.put("result", "1");
//        return map;
//    }

    @RequestMapping(value = {"/","login"},method = {RequestMethod.POST,RequestMethod.GET})
    public String login(Model model, HttpServletRequest request, HttpServletResponse response) {
        System.out.println(new Date() + ",run login");
        String token = TokenProccessor.getInstance().makeToken();
        request.getSession().setAttribute("token", token);
        model.addAttribute("token", token);
        Cookie[] cookies = request.getCookies();
        String username = "", password = "";
        if (cookies != null)
            for (Cookie c : cookies) {
                if (c.getName().equals("MovieWeb_username")) {
                    username = c.getValue();
//                    System.out.println("username" + username);
                } else if (c.getName().equals("MovieWeb_password")) {
                    password = c.getValue();
//                    System.out.println("password" + password);
                }
            }
        if (!username.equals("") && !password.equals("") && hasCookie) {
            return home(username, password, token, model, request, response);
        }
        return "login";
    }

    @RequestMapping(value = "logout" ,method = {RequestMethod.POST,RequestMethod.GET})
    public String logout(Model model, HttpServletRequest request, HttpServletResponse response) {
        System.out.println(new Date() + ",run logout");
        Cookie cookie = new Cookie("MovieWeb_username", "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        cookie = new Cookie("MovieWeb_password", "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        if (request.getSession().getAttribute("allow_token") != null) {
            request.getSession().removeAttribute("allow_token");
        }
        hasCookie = false;
        return login(model, request, response);
    }

    @RequestMapping("getAllUsers")
    public String getAllUsers(Model model) {
        List<UserInformation> users = this.userInformationService.getAllUsers();
        model.addAttribute("users", users);
        return "all";
    }

    private int getUserInformationId(String phone) {
        int id = 0;
        try {
            UserInformation userInformation = this.userInformationService.getUserInformationIdByPhone(phone);
            id = userInformation.getId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return id;
    }

    private boolean login(String phone, String password,HttpServletRequest request) {
        boolean success = false;
        try {
            int id = getUserInformationId(phone);
            String psw = userPasswordService.getPassword(id).getPassword();
//            password = Encrypt.getMD5(password);
            if (password.equals(psw)) {
                success = true;
                request.getSession().setAttribute("uid",id);
            }
        } catch (Exception e) {
            success = false;
            e.printStackTrace();
        }
        return success;
    }

    private UserInformation getUserInformation(String phone) {
        UserInformation userInformation = null;
        try {
            userInformation = this.userInformationService.getUserInformationById(getUserInformationId(phone));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return userInformation;
    }
}
